package com.XDApp.xdbase;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import com.XDApp.xdbase.xinsilu.R;

/**
 * 中间容器的管理工具
 * 
 * @author Administrator
 * 
 */
public class UIManager {
	private static UIManager instance = new UIManager();

	public static UIManager getInstance() {
		return instance;
	}

	private UIManager() {
	}

	/**
	 * 界面切换
	 * 
	 * @param target
	 */
	public void changeFragment(Fragment target, boolean isAddStack, Bundle bundle) {
		if (bundle != null) {
			target.setArguments(bundle);
		}

		FragmentManager manager = GloableParams.MAIN.getSupportFragmentManager();
		FragmentTransaction transaction = manager.beginTransaction();

		transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);

		// transaction.add(R.id.ii_middle, moreFragment);//
		// 第一参数：中间容器的id，第二个参数：添加的Fragment
		transaction.replace(R.id.ii_middle, target);

		// 返回键操作
		if (isAddStack)
			transaction.addToBackStack(null);

		transaction.commit();
	}

	public void switchContent(Fragment from, Fragment to) {
		FragmentManager manager = GloableParams.MAIN.getSupportFragmentManager();
		FragmentTransaction transaction = manager.beginTransaction().setCustomAnimations(
				android.R.anim.fade_in, android.R.anim.fade_out);
		if (!to.isAdded()) { // 先判断是否被add过
			transaction.hide(from).add(R.id.ii_middle, to).commit(); // 隐藏当前的fragment，add下一个到Activity中
		} else {
			transaction.hide(from).show(to).commit(); // 隐藏当前的fragment，显示下一个
		}
	}

	public void addFragment(Fragment target, boolean isAddStack, Bundle bundle) {
		if (bundle != null) {
			target.setArguments(bundle);
		}

		FragmentManager manager = GloableParams.MAIN.getSupportFragmentManager();
		FragmentTransaction transaction = manager.beginTransaction();

		transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);

		// transaction.add(R.id.ii_middle, moreFragment);//
		// 第一参数：中间容器的id，第二个参数：添加的Fragment
		transaction.add(R.id.ii_middle, target);

		// 返回键操作
		if (isAddStack)
			transaction.addToBackStack(null);

		transaction.commitAllowingStateLoss();
	}

	/**
	 * 添加一个fragment
	 * 
	 * @param id
	 *            容器
	 * @param fragment
	 *            将要添加的fragment
	 * @param hideFragment
	 *            隐藏的fragment
	 */
	public void addFragment(int id, Fragment fragment, Fragment hideFragment, Bundle bundle) {
		if (bundle != null) {
			fragment.setArguments(bundle);
		}
		FragmentTransaction ft = GloableParams.MAIN.getSupportFragmentManager().beginTransaction();
		ft.add(id, fragment);
		ft.hide(hideFragment);
		ft.addToBackStack(null);
		ft.commit();
	}
}
